<template>
    <div>
        <Breadcrumb :route="route.matched" />
    </div>
    <div class="wb-container">
        <div class="mian-content">
            <div class="deviceList-btn">
                <el-button style="background-color: #D4D7DE;" @click="router.push('/device/vendingMachine')"><el-icon>
                        <ArrowLeftBold />
                    </el-icon></el-button>
                <el-button style="background-color: #D4D7DE;" @click="isMqttShow = false">
                    {{ titleText }}
                </el-button>
                <el-button type="primary" @click="isMqttShow = true" v-if="editMqtt">修改MQTT</el-button>
            </div>
            <!-- 表单 -->
            <div class="device-form" v-if="!isMqttShow">
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                    :size="formSize" status-icon>
                    <el-form-item label="设备名称" prop="name">
                        <el-input v-model="ruleForm.name" class="elInputWidth" placeholder="请输入设备名称" />
                    </el-form-item>
                    <el-form-item label="称重板序号" prop="imei">
                        <el-input v-model="ruleForm.imei" class="elInputWidth" placeholder="请输入设备的IMEI,15位数字" />
                    </el-form-item>
                    <el-form-item label="安卓板序号" prop="android_imei">
                        <el-input v-model="ruleForm.android_imei" class="elInputWidth" placeholder="请输入安卓板的IMEI,15位数字" />
                    </el-form-item>
                    <el-form-item label="类型" prop="type" style="align-items: center;">
                        <el-radio-group v-model="ruleForm.type">
                            <el-radio label="1" size="large">称重板</el-radio>
                            <el-radio label="2" size="large">称重板/视觉板</el-radio>
                            <el-radio label="3" size="large">视觉板</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="流量卡ID" prop="sim_id">
                        <el-select v-model="ruleForm.sim_id" placeholder="请输入流量卡的ID">
                            <el-option v-for="item in simIdList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="安装地址" prop="address">
                        <el-select v-model="ruleForm.province" placeholder="请选择省份" clearable @change="selectChange">
                            <el-option v-for="item in list.economize" :key="item" :label="item.name" :value="item.name" />
                        </el-select>
                        <el-select v-model="ruleForm.city" placeholder="请选择城市" clearable @change="selectCityChange">
                            <el-option v-for="item in list.CityList" :key="item" :label="item.name" :value="item.name" />
                        </el-select>
                        <el-select v-model="ruleForm.area" placeholder="请选择区域" clearable>
                            <el-option v-for="item in list.region" :key="item" :label="item.name" :value="item.name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="" prop="address">
                        <el-input v-model="ruleForm.address" placeholder="请输入详细地址" class="form-input elInputWidth" />
                    </el-form-item>
                    <el-form-item label="状态" prop="enabled" style="align-items: center;">
                        <el-radio-group v-model="ruleForm.enabled">
                            <el-radio label="1" size="large">启用</el-radio>
                            <el-radio label="2" size="large">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="售货柜层数" prop="weighNum" v-if="isShow">
                        <el-input v-model="weighNumber" class="elInputWidth" placeholder="请输入售货柜的层数" />
                    </el-form-item>
                    <el-form-item label="门锁数量" prop="lockNum" v-if="isShow">
                        <el-input v-model="lockNumber" class="elInputWidth" placeholder="请输入售货柜门锁的数量" />
                    </el-form-item>
                    <el-form-item label="轮播视频" prop="video" class="typresStyle">
                        <div class="video">
                            <el-input v-model="ruleForm.ad_video_url" placeholder="上传轮播视频"
                                style="width:500px;height: 32px;" />
                            <el-upload ref="uploadRef" class="upload-demo" :show-file-list="false" :auto-upload="false"
                                :on-change="uploadChange">
                                <template #trigger>
                                    <el-button type="primary">上传</el-button>
                                </template>
                            </el-upload>
                        </div>
                        <div class="help-block">请上传小于100MB的MP4格式视频文件，请注意，上传视频后将优先播放于平台视频</div>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">提交</el-button>
                        <el-button @click="cancelClick(ruleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="mqttForm-class" v-if="isMqttShow">
                <el-form :model="mqttForm" label-width="120px">
                    <el-form-item label="用户名：" prop="username">
                        <el-input v-model="mqttForm.username" :title="mqttForm.username" />
                    </el-form-item>
                    <el-form-item label="密码：" prop="password">
                        <el-input v-model="mqttForm.password" :title="mqttForm.password" />
                    </el-form-item>
                    <el-form-item label="clientId：" prop="clientId">
                        <el-input v-model="mqttForm.clientId" :title="mqttForm.clientId" />
                    </el-form-item>
                    <el-form-item label="服务器地址：" prop="protocol">
                        <div class="hostname_class">
                            <el-select v-model="mqttForm.protocol">
                                <el-option v-for="item in protocolObj" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                            <el-input v-model="mqttForm.hostname" :title="mqttForm.hostname" />
                        </div>
                    </el-form-item>
                    <el-form-item label="端口：" prop="port">
                        <el-input v-model="mqttForm.port" :title="mqttForm.port" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="editMqttFormOnSubmit">修改</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ElButton, ElForm, ElMessage } from 'element-plus'
import { reactive, ref, onMounted } from 'vue'
import { GetCity, DeviceAdd, DeviceEdit, DeviceDetali } from '@/api/Device'
import { jsonFlatten } from '@/utlis/index'
import { uploadVideo, ProdBaseUrl } from '@/api/public'
import { simList } from '@/api/sim'
import { getDeviceMqttConfig, editDeviceMqttConfig } from "@/api/mqtt";
import { useStore } from 'vuex';
import { useRoute, useRouter } from "vue-router";
import Breadcrumb from "@/components/nav-header";

const route = useRoute()
const router = useRouter()
const store = useStore()
const formSize = ref('default')
const ruleFormRef = ref()
const uploadRef = ref()
const simIdList = ref()
const titleText = ref()
const isShow = ref(true)
const historyParam = ref(null)
const ruleForm = reactive({
    name: '',
    imei: '',
    android_imei: '',
    type: '1',
    sim_id: '',
    province: '',
    city: '',
    area: '',
    address: '',
    enabled: '1',
    ad_video_url: ''
})
const weighNumber = ref('')
const lockNumber = ref('')
//获得城市列表数据
const list = reactive({
    CityList: [],
    economize: [],
    region: []
})
const formName = /^[\u4E00-\u9FA5A-Za-z0-9]{2,30}$/
const imeiPattern = /^\d{15}$/
const androidPattern = /^\d{15}$/
const rules = reactive({
    name: [
        { required: true, pattern: formName, message: '输入2-30位的名字', trigger: ['blur'] },
    ],
    imei: [
        { required: true, pattern: imeiPattern, message: '请输入设备的IMEI,15位数字', trigger: 'blur' },
    ],
    android_imei: [
        { required: true, pattern: androidPattern, message: '请输入安卓板的IMEI,15位数字', trigger: 'blur' },
    ],
    sim_id: [
        { required: true, message: '选择流量卡', trigger: 'blur' },
    ],
    province: [
        { required: true, message: '选择省份', trigger: 'blur' },
    ],
    city: [
        { required: true, message: '选择市', trigger: 'blur' },
    ],
    area: [
        { required: true, message: '选择区', trigger: 'blur' },
    ],
    address: [
        { required: true, message: '填写详细地址', trigger: 'blur' },
    ]
})
const isMqttShow = ref(false)
const user = ref(JSON.parse(store.state.UserInfo))
const editMqtt = ref(false)
const mqttForm = ref({
    username: '',
    password: '',
    clientId: '',
    hostname: '',
    port: '',
    protocol: ''
})
const protocolObj = reactive([
    {
        label: 'ssl',
        value: 'ssl'
    },
    {
        label: 'mqtt',
        value: 'mqtt'
    },
    {
        label: 'tcp',
        value: 'tcp'
    },
])
const deviceId = ref('')
const getMqttFun = async () => {
    const result = await getDeviceMqttConfig(deviceId.value).then(res => {
        mqttForm.value = res
    })
}
//修改mqtt内容
const editMqttFormOnSubmit = async () => {
    mqttForm.value.device_id = deviceId.value
    delete mqttForm.value.id
    const edit = await editDeviceMqttConfig(mqttForm.value).then(s => {
        if (s == 1) {
            ElMessage.success('修改成功')
            getMqttFun()
        }
    })
}

//省份的id 
const getEconomizeList = async () => {
    try {
        const res = await GetCity({ pid: '0' }).then(r => {
            const { code, data } = r
            if (code == 200) {
                list.economize = data
            }
        })
    } catch (error) {
        alert(error)
    }
}
//获取流量卡列表
const getSim = async () => {
    const simData = await simList().then(res => {
        const { code, data } = res
        if (code == 200) {
            let list = data.data
            if (!list == null) {
                let s = list.map(it => {
                    return {
                        value: it.id,
                        label: it.phone
                    }
                })
                simIdList.value = s
            }
        }
    })
}
onMounted(() => {
    console.log(route.matched, '---------');
    getEconomizeList()
    getSim()
    historyParam.value = history.state.param
    if (historyParam.value) {
        titleText.value = "修改设备"
        isShow.value = false
        deviceId.value = historyParam.value.id
        let roleNmae = user.value.role_name
        if (roleNmae.includes('BOSS')) {
            editMqtt.value = true
            getMqttFun()
        } else {
            editMqtt.value = false
        }
        DeviceDetali(historyParam.value.id).then(r => {
            const { code, data } = r
            if (code == 200) {
                ruleForm.name = data.name
                ruleForm.imei = data.imei
                ruleForm.sim_id = data.sim_id
                ruleForm.android_imei = data.android_imei
                ruleForm.type = String(data.type)
                ruleForm.province = data.province
                ruleForm.city = data.city
                ruleForm.area = data.area
                ruleForm.address = data.address
                ruleForm.enabled = String(data.enabled)
                ruleForm.ad_video_url = data.ad_video_url
            }
        })
    } else {
        titleText.value = "添加设备"
        isShow.value = true
    }
})
const selectChange = async (val) => {
    let economize = list.economize.filter(item => {
        return item.name === val
    })
    let economizedata = jsonFlatten(economize)
    const data = await GetCity({ pid: economizedata.id })
    list.CityList = data
}
const selectCityChange = async (val) => {
    let city = list.CityList.filter(it => {
        return it.name === val
    })
    let cityData = jsonFlatten(city)
    const cityres = await GetCity({ pid: cityData.id })
    list.region = cityres
}
const onSubmit = async () => {
    ruleForm.sim_id = String(ruleForm.sim_id)
    if (historyParam.value) {
        const editData = await DeviceEdit(historyParam.value.id, ruleForm).then(res => {
            const { code, data } = res
            if (code == 200) {
                ElMessage.success('设备修改成功')
            }
        })
    } else {
        ruleForm.weighNum = weighNumber.value
        ruleForm.lockNum = lockNumber.value
        let AddForm = JSON.parse(JSON.stringify(ruleForm))
        const addData = await DeviceAdd(AddForm).then(r => {
            const { code, data } = r
            if (code == 200) {
                ElMessage.success('添加成功')
            }
        })
    }
}
const cancelClick = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
//上传文件
const uploadChange = async (file) => {
    const isLt100M = file.size / 1024 / 1024 < 100;
    if (['video/mp4'].indexOf(file.raw.type) == -1) {
        ElMessage.error('请上传正确的视频格式');
        return false;
    }
    if (!isLt100M) {
        ElMessage.error('上传视频大小不能超过100MB哦!');
        return false;
    }
    let fd = new FormData()
    fd.append('video', file.raw)
    const video = await uploadVideo(fd).then(r => {
        const { code, data } = r
        if (code == 200) {
            let videoUpload = ProdBaseUrl + data.slice(7)
            ruleForm.ad_video_url = videoUpload
            ElMessage.success('视频上传成功')
        }
    })
}
</script>
<style lang="less" scoped>
.deviceList-btn {
    padding: 10px 0 10px 10px;
    border-bottom: 1px solid #f0f0f0;
}

.device-form {
    padding: 20px;
}

.page-sub-toolbar {
    width: 100%;
    padding-bottom: 15px;
    height: 45px;
    line-height: 1;
    vertical-align: middle;
    margin-bottom: 15px;
    border-bottom: 1px solid #efefef;
}

.page-sub-toolbar span {
    padding: 8px 10px;
    border: 1px solid #efefef;
    border-radius: 5px;
    background-color: #44abf7;
    color: #fff;
}

.btn {
    outline: none !important;
    padding: 8px 16px;
    border-radius: 2px;
    font-size: 12px;
    line-height: 1;
    color: #fff;
    text-align: center;
    vertical-align: middle;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    cursor: pointer;
    -webkit-transition: background-color 0.3s;
    -moz-transition: background-color 0.3s;
    transition: background-color 0.3s;
    border: 1px solid transparent;
}

.btn-sm {
    display: inline-block;
    padding: 7px 8px;
    border-radius: 2px;
    font-size: 12px;
    line-height: 1;
    color: #fff;
    background: #dddddd;
    text-align: center;
    vertical-align: middle;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    cursor: pointer;
    -webkit-transition: background-color 0.3s;
    -moz-transition: background-color 0.3s;
    transition: background-color 0.3s;
}

.btn-primary {
    background: #44abf7 !important;
    border-color: #44abf7 !important;
    color: #fff !important;
}

:deep(.typresStyle .el-form-item__content) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

:deep(.el-button) {
    letter-spacing: 2px;
}

.form-input {
    margin-top: 15px;
}

.video {
    display: flex;
}

.help-block {
    display: block;
    margin-top: 5px;
    margin-bottom: 10px;
    color: #737373;
}

.elInputWidth {
    width: 700px;
}

.mqttForm-class {
    height: 600px;
    padding: 20px;

    .hostname_class {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}

@media screen and (min-width: 768px) {
    .mqttForm-class {
        width: 100%;
    }
}

@media screen and (min-width: 992px) {
    .mqttForm-class {
        width: 60%;
    }
}
</style>